package com.etone.smartAudit.handleType;

import com.alibaba.fastjson.JSONArray;
import com.etone.smartAudit.vo.FileVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: sovy
 * @date: 2020/9/24
 * @description: json字符串转List<FileVo>,用于sql中FileVO数组字段映射
 */
public class FileListTypeHandler extends BaseTypeHandler<List<FileVO>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<FileVO> objects, JdbcType jdbcType) throws SQLException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            preparedStatement.setString(i, mapper.writeValueAsString(objects));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<FileVO> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return JSONArray.parseArray(resultSet.getString(s), FileVO.class);

    }

    @Override
    public List<FileVO> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public List<FileVO> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}